var layer = layui.layer //弹层
    ,table = layui.table //表格
form = layui.form,$ = layui.jquery,laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});


function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


//select over
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        getxmselect("#operationCode","operationCode", userTree);
        getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        getxmselect("#salesmanCode","salesmanCode", []);
    }
})()


layer.ready(function () {
    $.ajax({
        url: 'billChange/selectAllcompanyAndpeople',
        type: 'GET',
        success: function (date) {
            var map=date.data
            var company=[]
            $.each(map, function (key, value) {
                if(key=="companyName"){
                    company=value
                }
            });
            for(let i in company){
                $("#company_code").append("<option value='"+company[i].code+"'>"+company[i].name+"</option>")
            }

            form.render();
        }
    });

});
table.render({
    elem: '#mains'
    ,url:'billChange/selectAllchangeByPage'
    , where: {
        operationCode:user.code ,
    }
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'billId', hide:true}
        ,{field:'companyName', title:'签约公司 ',sort:true}
        ,{field:'companyCode', hide:true}
        ,{field:'invoiceNo', title:'发票编号',sort:true}
        ,{field:'customerName', title:'客户名称',sort:true}
        ,{field:'custCode', hide:true}
        ,{field:'invoiceDate', title:'发票日期',sort:true}
        ,{field:'shippingDate', title:'出运日期',sort:true}
        ,{field:'settleDate', title:'预计收汇日期',sort:true}
        ,{field:'priceTerm', title:'价格术语',sort:true}
        ,{field:'createTime', title:'制单日期',sort:true}
        ,{field:'contractNo', title:'销售合同号',sort:true}
        ,{field:'salesman', title:'业务员',sort:true}
        ,{field:'opname', title:'操作员',sort:true}
        ,{field:'businessMode', title:'业务模式',sort:true}
        ,{field:'linker', title:'联系人',sort:true}

    ]]
    ,id: 'mainstableid'
    ,height: 500
    ,page: true
});

form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    var purchaseorderdata =   table.checkStatus("mainstableid").data;
    if(purchaseorderdata.length == 0){
        layer.msg("请选择数据")
    }else{
        var oldData =  parent.table.cache["moaidetailtableid"];
        $.each(purchaseorderdata, function (index, value) {
            //外销合同号
            let invoiceNo=value.invoiceNo;
            let billId=value.billId;
            let arr=[];
            $.ajax({
                url:'billing/getBillExchangeProductList',
                type:"POST",
                data:{invoiceNo:invoiceNo,billId:billId},
                async:false,
                success:function (data) {
                    arr=data.data;
                }
            })
            let newArr=[];
            for (let i = 0; i < arr.length; i++) {
                let newTemp = {};
                newTemp.tempId=Number(Math.random().toString().substr(3,3) + Date.now()).toString(36);
                newTemp.saleContractCode=value.invoiceNo;
                newTemp.companyName=value.companyName;
                newTemp.companyCode=value.companyCode;
                newTemp.supplyCode=value.custCode;
                newTemp.supplyName=value.customerName;
                newTemp.linker = value.linker;

                newTemp.stockCode=arr[i].purchaseOrderNo;
                newTemp.goodsCode= arr[i].productNo;
                newTemp.specCode= arr[i].specNo;
                newTemp.goodsSpec= arr[i].normExplain;
                newTemp.goodsCname= arr[i].chineseName;
                newTemp.goodsEname= arr[i].englishName;
                newTemp.goodsCdesc= arr[i].chineseDesc;
                newTemp.goodsEdesc= arr[i].englishDesc;
                newTemp.goodsNum= arr[i].amount;
                newTemp.goodsUnit= arr[i].unit;
                newTemp.invoiceUnitPrice= arr[i].price;
                newTemp.invoiceSubtotal= arr[i].subtotal;
                newTemp.colour= arr[i].color;
                newTemp.goodsGross= arr[i].grossWeight;
                newTemp.totalGross= arr[i].grossSubtotal;
                newTemp.netWeight= arr[i].netWeight;
                newTemp.totalNet= arr[i].netSubtotal;
                newTemp.bulk= arr[i].volume;
                newTemp.purchaseUnitPrice= arr[i].price;
                newTemp.unitCost= arr[i].price;
                newTemp.costSubtotal= arr[i].subtotal;
                newTemp.declarePrice= 0;
                newTemp.totalPrice= 0;
                newTemp.productType= parseInt(arr[i].purchaseType);
                newTemp.invoiceType= 4;//开票单据来源（1导入报关，2导入采购，3导入外销，4导入结汇）
                newArr.push(newTemp);
            }

            oldData.push.apply(oldData,newArr);
        });
        parent.table.reload('moaidetailtableid',{data : oldData}); //刷新主信息表格
        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000)
    }
})
$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})